package com.sgb.kjwl.view.ui.fragment.material;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.callback.OnTabSelectedListener;
import com.sgb.kjwl.databinding.AllcommodityFragmentBinding;
import com.sgb.kjwl.di.material.DaggerMaterialFragComponent;
import com.sgb.kjwl.di.material.MaterialFragModule;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.model.entity.user.MaterChooseEntity;
import com.sgb.kjwl.model.entity.user.TwoOrThreeLevelEntity;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.MaterialEvent;
import com.sgb.kjwl.view.ui.adapter.material.MatterAdapter;
import com.sgb.kjwl.view.ui.adapter.search.MaterialAdapter;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.home.AllCommodityModule;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/4/5 0005
 * 说明:全部商品的fragment
 */

@Deprecated
public class AllCommodityFragment extends AppLazyFragment {
    @Inject
    AllCommodityModule mModel;

    private AllcommodityFragmentBinding mBinding;
    private List<MenuEntity> mGoodsType;
    private String mOneType;
    private String mTwoType;
    private String mThreeType;
    private String mIndustry;
    private int mWhereJump;
    private List<TwoOrThreeLevelEntity> mTwoLevelEntities;
    private List<TwoOrThreeLevelEntity> mThreeLevelEntities;
    private MatterAdapter mAdapter;
    private int mPageNum = 1;
    private String mCid1;
    private String mCid3;
    private String mCategoryId;
    private String mLon = "0";
    private String mLat = "0";
    private MaterialAdapter mMaterialAdapter;
    private boolean mIsMore;
    private HashMap mHashMap;
    private ThreeLevelAreaWindow mThreeLevelPopWindow;
    private String mProvince;
    private String mCityId;
    private String mArea;
    private List<String> mAreaId = new ArrayList<>();


    public static AllCommodityFragment newInstance(int type, List<MenuEntity> goodsType, String position, int whereJump) {
        AllCommodityFragment allCommodityFragment = new AllCommodityFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putInt("whereJump", whereJump);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putString("childPosition", position);
        allCommodityFragment.setArguments(bundle);
        return allCommodityFragment;
    }

    public static AllCommodityFragment newInstance(int type, List<MenuEntity> goodsType, String position, String industry, String obligate) {
        AllCommodityFragment allCommodityFragment = new AllCommodityFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putString("childPosition", position);
        bundle.putString("industry", industry);
        bundle.putString("obligate", obligate);
        allCommodityFragment.setArguments(bundle);
        return allCommodityFragment;
    }

    public static AllCommodityFragment newInstance(int type, List<MenuEntity> goodsType, String id, String one, String two, String three) {
        AllCommodityFragment allCommodityFragment = new AllCommodityFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("goodsListType", type);
        bundle.putSerializable("goodsList", (Serializable) goodsType);
        bundle.putString("childPosition", id);
        bundle.putString("one", one);
        bundle.putString("two", two);
        bundle.putString("three", three);
        allCommodityFragment.setArguments(bundle);
        return allCommodityFragment;
    }


    @Override
    protected void onLazyLoad() {
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMaterialFragComponent.builder()
                .appComponent(appComponent)
                .materialFragModule(new MaterialFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.allcommodity_fragment, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        super.initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mWhereJump = getArguments().getInt("whereJump", 0);
        mGoodsType = (List<MenuEntity>) getArguments().getSerializable("goodsList");
        mOneType = getArguments().getString("one");
        mTwoType = getArguments().getString("two");
        mThreeType = getArguments().getString("three");
        mIndustry = getArguments().getString("industry");
        mProvince = getArguments().getString("province");
        mProvince = mProvince == null ? "" : mProvince;
        mBinding.rvGoodMatterChoose.setLayoutManager(new LinearLayoutManager(UiUtil.getContext(), LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new MatterAdapter(null);
        mBinding.rvGoodMatterChoose.setAdapter(mAdapter);
        mBinding.xrvFragmentGoodsMainGoodsList.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
        mMaterialAdapter = new MaterialAdapter(getContext(), null, false);
        mBinding.xrvFragmentGoodsMainGoodsList.setAdapter(mMaterialAdapter);
        mThreeLevelPopWindow = new ThreeLevelAreaWindow(getContext()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                if (!mProvince.equals(baseAreaEntity.getId()))
                    mCityId = "";
                mProvince = baseAreaEntity.getId();
                mArea = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                if (!mCityId.equals(baseAreaEntity.getId())) {
                    mAreaId.clear();
                    mArea = "";
                }
                mCityId = baseAreaEntity.getId();
                mArea = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void areaMoreClick(List list, int position) {
                mAreaId.clear();
                mArea = "";
                for (Object o : list) {
                    BaseAreaEntity baseAreaEntity = (BaseAreaEntity) o;
                    if (!mAreaId.contains(baseAreaEntity.getId())) {
                        mAreaId.add(baseAreaEntity.getId());
                    }
                    if (!mArea.contains(baseAreaEntity.getSimpleName())) {
                        mArea = baseAreaEntity.getSimpleName();
                    }
                }
            }
        };
        mThreeLevelPopWindow.setShowSimpleName(true);
        mThreeLevelPopWindow.setBgView(mBinding.grayLayout);
        mThreeLevelPopWindow.setAreaMore();
        mThreeLevelPopWindow.setCitySingle();
        mThreeLevelPopWindow.setProvinceSingle();
        mThreeLevelPopWindow.setOnResultClick((key1, key2, key3) -> {
            getGoods(false);
        });
        initData();
        initListener();
    }


    private void initData() {
        // 一级
        for (int i = 0; i < mGoodsType.size(); i++) {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle1.newTab().setText(mGoodsType.get(i).getName()));
            if (mGoodsType.get(i).getId().equals(mOneType)) {
                int finalI = i;
                mBinding.tlFragmentGoodsMainGoodsSelectTitle1.postDelayed(() -> mBinding.tlFragmentGoodsMainGoodsSelectTitle1.getTabAt(finalI).select(), 100);
            }
        }
    }

    private void initListener() {
        mThreeLevelPopWindow.setOnDisMissClick(() -> {
            if (mArea.equals("") || mArea.equals("不限")) {
                mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelect(false, false);
            } else {
                mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelect(true, false);
            }
        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            MaterChooseEntity materChooseEntity = mAdapter.getData().get(position);
            UiUtil.showToast(materChooseEntity.getName());
        });
        mBinding.xrvFragmentGoodsMainGoodsList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getGoods(false);
            }

            @Override
            public void onLoadMore() {
                getGoods(true);
            }
        });
        // 地区
        mBinding.tvFragmentGoodsMainGoodsListSelect1.setOnClickListener(v -> {
            mBinding.tvFragmentGoodsMainGoodsListSelect1.contentSelect(false, true);
            mThreeLevelPopWindow.showPopwindow(mBinding.llFragmentGoodsMainGoodsListSelect, 0, 0);
        });
        // 距离
        mBinding.tvFragmentGoodsMainGoodsListSelect2.setOnClickListener(v -> {

        });

        // 一级tab选种监听
        mBinding.tlFragmentGoodsMainGoodsSelectTitle1.addOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mCid1 = mGoodsType.get(tab.getPosition()).getId();
                mBinding.tlFragmentGoodsMainGoodsSelectTitle2.setVisibility(tab.getPosition() == 0 ? View.GONE : View.VISIBLE);
                mBinding.tvFragmentGoodsMainGoodsListSelect2.setVisibility(tab.getPosition() == 0 ? View.GONE : View.VISIBLE);
                mBinding.ivFragmentGoodsMainGoodsTag2.setVisibility(tab.getPosition() == 0 ? View.GONE : View.VISIBLE);
                if (tab.getPosition() == 0) {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle2.removeAllTabs();
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
                    mBinding.rvGoodMatterChoose.setVisibility(View.GONE);
                    mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(View.GONE);
                    mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(View.GONE);
                    mCid3 = mCategoryId = "";
                    getGoods(false);
                } else {
                    mModel.getTwoOrThreeLevelData(mGoodsType.get(tab.getPosition()).getId(), 0);
                }
            }
        });
        // 二级tab选种监听
        mBinding.tlFragmentGoodsMainGoodsSelectTitle2.addOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mCategoryId = mTwoLevelEntities.get(tab.getPosition()).getId();
                mBinding.tlFragmentGoodsMainGoodsSelectTitle3.setVisibility(tab.getPosition() == 0 ? View.GONE : View.VISIBLE);
                mBinding.ivFragmentGoodsMainGoodsTag3.setVisibility(tab.getPosition() == 0 ? View.GONE : View.VISIBLE);
                if (tab.getPosition() == 0) {
                    mBinding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
                    mBinding.rvGoodMatterChoose.setVisibility(View.GONE);
                    mCid3 = "";
                    if (UiUtil.isEmpty(mTwoType)) {
                        getGoods(false);
                    }
                } else {
                    mModel.getTwoOrThreeLevelData(mTwoLevelEntities.get(tab.getPosition()).getId(), 1);
                }
            }
        });
        // 三级tab选种监听
        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.addOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mCid3 = mThreeLevelEntities.get(tab.getPosition()).getId();
                mBinding.rvGoodMatterChoose.setVisibility(View.VISIBLE);
                mModel.getMaterialBrand(mThreeLevelEntities.get(tab.getPosition()).getId());
                if (tab.getPosition() == 0) {
                    if (UiUtil.isEmpty(mThreeType)) {
                        getGoods(false);
                    }
                } else {
                    getGoods(false);
                }
            }
        });
    }


    // 二级数据
    public void setTwoLevelData(List<TwoOrThreeLevelEntity> data) {
        mBinding.tlFragmentGoodsMainGoodsSelectTitle2.removeAllTabs();
        mTwoLevelEntities = data;
        for (int i = 0; i < data.size(); i++) {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle2.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle2.newTab().setText(data.get(i).getName()));
            if (data.get(i).getId().equals(mTwoType == null ? "" : mTwoType)) {
                int finalI = i;
                mBinding.tlFragmentGoodsMainGoodsSelectTitle2.postDelayed(() -> mBinding.tlFragmentGoodsMainGoodsSelectTitle2.getTabAt(finalI).select(), 100);
                mTwoType = "";
            }
        }
    }

    // 三级数据
    public void setThreeLevelData(List<TwoOrThreeLevelEntity> data) {
        mBinding.tlFragmentGoodsMainGoodsSelectTitle3.removeAllTabs();
        mThreeLevelEntities = data;
        for (int i = 0; i < data.size(); i++) {
            mBinding.tlFragmentGoodsMainGoodsSelectTitle3.addTab(mBinding.tlFragmentGoodsMainGoodsSelectTitle3.newTab().setText(data.get(i).getName()));
            if (data.get(i).getId().equals(mThreeType == null ? "" : mThreeType)) {
                int finalI = i;
                mBinding.tlFragmentGoodsMainGoodsSelectTitle3.postDelayed(() -> mBinding.tlFragmentGoodsMainGoodsSelectTitle3.getTabAt(finalI).select(), 100);
                mThreeType = "";
            }
        }
    }

    public void setMaterialBrandData(List<MaterChooseEntity> list) {
        mAdapter.setNewData(list);
    }


    public void getGoods(boolean isMore) {
        if (mHashMap == null) {
            mHashMap = new HashMap();
        }
        mPageNum = isMore ? mPageNum + 1 : 1;
        mIsMore = isMore;
        mHashMap.put("pageNum", mPageNum);
        mHashMap.put("pageSize", 20);
        mHashMap.put("cid1", mCid1);
        mHashMap.put("cid3", mCid3);
        mHashMap.put("categoryId", mCategoryId);
        mHashMap.put("regionCode", mAreaId);
        mHashMap.put("areaId", mCityId);
        mHashMap.put("distance", "");
        mHashMap.put("timeSort", "2");
        mHashMap.put("priceSort", "0");
        mHashMap.put("brandId", new ArrayList<>());
        mHashMap.put("materValue", "");
        mHashMap.put("lon", mLon.equals("0") ? SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE, "") : mLon);
        mHashMap.put("lat", mLat.equals("0") ? SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE, "") : mLat);
        mModel.getGoodsList(mHashMap);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void getCode(MaterialEvent event) {
        switch (event.getMessageTag()) {
            case EventConstant.EVENT_GOODS_LOC:
                mLon = (String) event.getObject();
                mLat = (String) event.getMessageData();
                System.out.println("接收到定位==lon=" + mLon + "\tlat==" + mLat);
                break;
        }
    }

    public void getGoodsList(List<GoodsListEntity> data) {
        mBinding.xrvFragmentGoodsMainGoodsList.refreshComplete();
        if (mIsMore) {
            if (null != data && data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.loadMoreComplete();
                mMaterialAdapter.addDatas(data);
            } else {
                mBinding.xrvFragmentGoodsMainGoodsList.setNoMore(true);
            }
            mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
        } else {
            mBinding.xrvFragmentGoodsMainGoodsList.refreshComplete();
            if (null != data && data.size() > 0) {
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.nsvEmpty.setVisibility(View.GONE);
                mMaterialAdapter.setDatas(data);
                mBinding.xrvFragmentGoodsMainGoodsList.setLoadingMoreEnabled(true);
            } else {
                mMaterialAdapter.setDatas(null);
                mBinding.xrvFragmentGoodsMainGoodsList.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.nsvEmpty.setVisibility(View.VISIBLE);
            }
        }
    }
}